<template>
  <div class="login">
    <el-tabs type="border-card">
        <el-tab-pane label="密码登录">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
      <el-form-item style="margin-bottom: 0;">
        <div class="other-login-box">
          <img @click="handleSocialLogin('gitee')" src="../assets/logo/gitee.png" title="使用码云登录">
          <img @click="handleSocialLogin('github')" src="../assets/logo/github.png" title="使用github登录">
          <img @click="handleSocialLogin('dingtalk')" src="../assets/logo/dingtalk.png" title="使用钉钉登录">
          <img @click="handleSocialLogin('qq')" src="../assets/logo/qq.png" title="使用qq登录">
          <img @click="handleSocialLogin('wechat')" src="../assets/logo/wechat.png" title="使用微信登录">
          <img @click="handleSocialLogin('weibo')" src="../assets/logo/weibo.png" title="使用微博登录">
        </div>
        <div id="login_container"></div>
      </el-form-item>
    </el-form>
      </el-tab-pane>
      <el-tab-pane label="免密登录">
        <el-form ref="smsLoginForm" :model="smsLoginForm" :rules="smsLoginRules" class="login-form">
          <el-form-item prop="phoneNumber">
            <el-input style="width: 60%" v-model.number="smsLoginForm.phoneNumber" type="text" auto-complete="off" placeholder="手机号码">
              <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
            </el-input>
            <el-button class="login-code"
              :loading="loading"
              size="small"
              type="primary"
              style="width: 35%;"
              :disabled="!smsLoginForm.show"
              @click.native.prevent="sendValidCode"
            >
              获取验证码
              <span v-show="!smsLoginForm.show" class="count">({{smsLoginForm.count}}s)</span>
            </el-button>
          </el-form-item>
          <el-form-item prop="validCode">
            <el-input v-model="smsLoginForm.validCode" type="text" auto-complete="off" placeholder="验证码">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleSmsLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2019 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>
<script>
  import {getCodeImg} from "@/api/login";
  import {sendValidCode} from "@/api/smsg/smsg";
  import Cookies from "js-cookie";
  import {decrypt, encrypt} from '@/utils/jsencrypt'

  export default {
  name: "Login",

  data() {
    // 手机号验证
    const validatePhoneNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的手机号"));
        } else {
          callback();
        }
      }
    }
    // 验证码验证
    const validateValidCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        if (!/^\d{4}$/.test(value)) {
          callback(new Error("请输入正确的4位数字验证码"));
        } else {
          callback();
        }
      }
    }
    return {
      codeUrl: "",
      cookiePassword: "",
      socialList: ['gitee', 'github', 'dingtalk', 'qq', 'wechat', 'weibo'],
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      smsLoginForm: {
        show: true, // 初始启用按钮
        count: '', // 初始化次数
        timer: null,
        phoneNumber: '',
        validCode: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      smsLoginRules: {
        phoneNumber: [
          { required: true, trigger: "blur", message: "手机号码不能为空" },
          { validator: validatePhoneNumber, trigger: "blur"}
        ],
        validCode: [
          { required: true, trigger: "blur", message: "验证码不能为空" },
          { validator: validateValidCode, trigger: "blur"}
        ],
      },
      loading: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    handleSmsLogin() {
      this.loading = true;
      this.$refs.smsLoginForm.validate(valid => {
        if(valid) {
          let data = {
            phoneNumber: this.smsLoginForm.phoneNumber,
            validCode: this.smsLoginForm.validCode
          }
          this.$store.dispatch("SmsLogin", data)
            .then(() => {
              this.msgSuccess("登录成功")
              this.$router.push({ path: this.redirect || "/" });
            }).catch(() => { this.loading = false });
        } else {
          this.loading = false;
        }
      });
    },
    sendValidCode() {
      this.$refs.smsLoginForm.validateField('phoneNumber', valid => {
        if(!valid) {
          const TIME_COUNT = 60 //更改倒计时时间,
          if (!this.timer) {
            this.smsLoginForm.count = TIME_COUNT;
            this.smsLoginForm.show = false;
            this.smsLoginForm.timer = setInterval(() => {
              if (this.smsLoginForm.count > 0 && this.smsLoginForm.count <= TIME_COUNT) {
                this.smsLoginForm.count--;
              } else {
                this.clearTimer()
              }
            }, 1000)
          }
          sendValidCode({phoneNumber: this.smsLoginForm.phoneNumber})
            .then(res => {
              if (res == 'success') {
                this.msgSuccess('发送验证码成功');
              } else {
                this.clearTimer()
                this.msgError(res)
              }
            })
        }
      });
    },
    handleSocialLogin(systemId) {
      this.loading = true;
      // 后端服务器oauth2登录获取授权码的地址
      let url = process.env.VUE_APP_SERVER_URL + "/social/authorize/" + systemId
      // 弹出 500 * 500 的窗口
      window.open(url, 'newwindow', 'height=500, width=500, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
      // 通过监听，父页面可以拿到子页面传递的token，父(前端页面)，子(小窗)
      let that = this;
      window.addEventListener('message', function (e) {
        if(e.data != undefined && e.data.substring(0,5) == "error") {
          that.msgError(systemId + "账号登录失败，请重试\n" + e.data)
          console.log(e.data);
        } else {
          that.$store
            .dispatch("SocialLogin", e.data)
            .then(() => {
              that.msgSuccess(systemId + "账号登录成功")
              that.$router.push({ path: that.redirect || "/" });
            }).catch(() => {
              that.getCode();
          });
        }
        that.loading = false
      }, false)
    },
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    },
    clearTimer() {
      this.smsLoginForm.show = true;
      clearInterval(this.smsLoginForm.timer); // 清除定时器
      this.smsLoginForm.timer = null;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
  .el-tabs {
    padding: 0;
    border-radius: 12px;
  }
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/image/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 5px 10px 5px 10px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
  .other-login-box {
    float: right;
    img {
      width: 32px;
      height: 32px;
      margin-left: 5px;
      background-color: #ffffff;
      border-radius: 50%;
      cursor: pointer;
    }
  }
</style>
